﻿using System;
using System.Transactions;
using System.Collections.Generic;

namespace FlashPay.Service.Impl
{
    using FlashPay.DAO.Interface;
    using FlashPay.EF;
    using FlashPay.EF.Models;
    using FlashPay.Entity;
    using FlashPay.Entity.Enum;
    using FlashPay.Entity.Parameter;
    using FlashPay.Entity.Request.User;
    using FlashPay.Entity.Response.Company;
    using FlashPay.Entity.Response.Role;
    using FlashPay.Entity.Response.User;
    using FlashPay.Service.Interface;
    using FlashPay.Util;
    using Microsoft.AspNetCore.Http;
    using Newtonsoft.Json;
    using System.Linq;

    /// <summary>
    /// 用户业务接口实现
    /// </summary>
    public class UserInfoServiceImpl : UserInfoService
    {
        /// <summary>
        /// 用户数据接口
        /// </summary>
        private readonly UserInfoDao _userInfo;

        /// <summary>
        /// 用户角色数据接口
        /// </summary>
        private readonly UserRoleDao _userRole;

        /// <summary>
        /// 用户数据接口
        /// </summary>
        private readonly MenuDao _menuDao;

        /// <summary>
        /// 授权数据接口
        /// </summary>
        private readonly AuthorizeDao _authorizeDao;

        /// <summary>
        /// 功能权限数据接口
        /// </summary>
        private readonly PermissionDao _permissionDao;

        /// <summary>
        /// 日志权限数据接口
        /// </summary>
        private readonly LogDao _logDao;

        /// <summary>
        /// 日志模型
        /// </summary>
        private readonly LogRecord _logRecord;

        /// <summary>
        /// 公司角色
        /// </summary>
        private readonly SysRoleDao _roleDao;

        /// <summary>
        /// 公司数据接口
        /// </summary>
        private readonly CompanyDao _companyDao;

        /// <summary>
        /// 缓存
        /// </summary>
        private readonly MemoryCacheUtil _memoryCacheUtil;

        /// <summary>
        /// 上下文
        /// </summary>
        private FlashPayContext _context { set; get; }

        /// <summary>
        /// 
        /// </summary>
        private IHttpContextAccessor _accessor;

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="userInfo">用户数据接口</param>
        public UserInfoServiceImpl(AuthorizeDao authorizeDao, PermissionDao permissionDao, UserInfoDao userInfo, MenuDao menuDao, LogDao logDao, UserRoleDao userRole, SysRoleDao srlDao, LogRecord logRecord, CompanyDao companyDao, MemoryCacheUtil memoryCacheUtil, FlashPayContext context, IHttpContextAccessor accessor)
        {
            this._authorizeDao = authorizeDao;
            this._permissionDao = permissionDao;
            this._userInfo = userInfo;
            this._menuDao = menuDao;
            this._logDao = logDao;
            this._userRole = userRole;
            this._roleDao = srlDao;
            this._logRecord = logRecord;
            this._companyDao = companyDao;
            this._memoryCacheUtil = memoryCacheUtil;
            this._context = context;
            this._accessor = accessor;
        }

        /// <summary>
        /// 根据编号获取公司
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Company</returns>
        public JResult<UserInfoResponse> Get(int id)
        {
            var result = new JResult<UserInfoResponse>() {
                Success = false
            };

            var userInfo = _userInfo.Get(id);
            if (userInfo != null) {
                var userInfoResponse = new UserInfoResponse() {
                    UId = userInfo.UId,
                    UCompanyId = userInfo.UCompanyId,
                    ULoginName = userInfo.ULoginName,
                    UPwd = userInfo.UPwd,
                    UEmail = userInfo.UEmail,
                    UTelephone = userInfo.UTelephone,
                    UStatus = userInfo.UStatus,
                    UDescription = userInfo.UDescription,
                    UUiconfig = userInfo.UUiconfig,
                    USecretKey = userInfo.USecretKey,
                    ULoggedIn = userInfo.ULoggedIn,
                };

                result.Success = true;
                result.Data = userInfoResponse;
            }

            return result;
        }

        /// <summary>
        /// 根据编号获取公司
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Company</returns>
        public JResult<UserInfoResponse> GetById(TicketResponse ticketResponse, int? id)
        {
            var userInfoResponse = new JResult<UserInfoResponse>()
            {
                Success = false,
                Data = new UserInfoResponse()
                {
                    CompanyResponse = new List<CompanyResponse>() { },
                    AuthCompanyResponse = new List<CompanyResponse>() { },
                    RoleResponse = new List<RoleResponse>(),
                    IsAuth = true
                }
            };

            try
            {
                #region 公司列表
                /*
                 * 1、显示自己所属公司
                 * 2、显示当前用户创建的公司
                */
                var companyResponse = new List<CompanyResponse>();
                var authCompanyResponse = new List<CompanyResponse>();
                var companys = GetCompany(ticketResponse.CompanyID, 2);

                if (companys != null && companys.Any())
                {
                    foreach (var item in companys)
                    {
                        companyResponse.Add(new CompanyResponse()
                        {
                            CompanyID = item.CompanyID,
                            CompanyName = item.CompanyName,
                        });

                        if (item.CreateUID == ticketResponse.UserID || item.CompanyID == ticketResponse.CompanyID)
                        {
                            authCompanyResponse.Add(new CompanyResponse()
                            {
                                CompanyID = item.CompanyID,
                                CompanyName = item.CompanyName,
                            });
                        }
                    }
                    userInfoResponse.Data.CompanyResponse.AddRange(companyResponse);
                    userInfoResponse.Data.AuthCompanyResponse.AddRange(authCompanyResponse);
                }

                #endregion

                if (id.HasValue)
                {
                    var userInfo = _userInfo.Get(id.Value);
                    if (userInfo != null)
                    {
                        userInfoResponse.Data.UId = userInfo.UId;
                        userInfoResponse.Data.UCompanyId = userInfo.UCompanyId;
                        userInfoResponse.Data.ULoginName = userInfo.ULoginName;
                        userInfoResponse.Data.UPwd = userInfo.UPwd;
                        userInfoResponse.Data.UEmail = userInfo.UEmail;
                        userInfoResponse.Data.UTelephone = userInfo.UTelephone;
                        userInfoResponse.Data.UStatus = userInfo.UStatus;
                        userInfoResponse.Data.UDescription = userInfo.UDescription;
                        userInfoResponse.Data.UUiconfig = userInfo.UUiconfig;
                        userInfoResponse.Data.USecretKey = userInfo.USecretKey;
                        userInfoResponse.Data.ULoggedIn = userInfo.ULoggedIn;
                        userInfoResponse.Data.IsAuth = ticketResponse.UserID == userInfo.UCreateId;
                        var company = _menuDao.GetById(userInfo.UCompanyId);
                        if (company != null)
                        {
                            userInfoResponse.Data.CompanyName = company.CompanyName;
                        }
                    }

                    var roleResponse = new List<RoleResponse>();

                    //已选择角色
                    var selectedRole = _roleDao.GetByUserId(userInfo.UId);

                    selectedRole.ForEach(item =>
                    {
                        roleResponse.Add(new RoleResponse()
                        {
                            RId = item.RId,
                            RName = item.RName
                        });
                    });

                    userInfoResponse.Data.RoleResponse = roleResponse;
                }
                else
                {

                }

                userInfoResponse.Success = true;
            }
            catch (Exception ex)
            {

            }

            return userInfoResponse;
        }

        #region 根据编号获取公司
        /// <summary>
        /// 根据编号获取公司
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Company</returns>
        private List<CompanyResponse> GetCompany(int companyId, int level)
        {
            var companyRequest = new EF.Models.Company()
            {
                CompanyId = companyId,
                CompanyPid = -1,
                CompanyStatus = 1
            };

            var companyList = new BaseModel<List<EF.Models.Company>>();

            _companyDao.Get(companyList, companyRequest, level);
            var companyResponse = new List<CompanyResponse>();
            if (companyList.Success)
            {
                foreach (var item in companyList.Result)
                {
                    companyResponse.Add(new CompanyResponse()
                    {
                        CompanyID = item.CompanyId,
                        CompanyName = item.CompanyName,
                        CompanyStatus = item.CompanyStatus,
                        CreateUID = item.CreateUid
                    });
                }
            }
            return companyResponse;
        }
        #endregion

        #region 登录
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        public JResult<LoginResponse> Login(LoginRequest request)
        {

            var response = new JResult<LoginResponse>()
            {
                Success = false
            };
            //加密码
            var desPass = EncryptHelper.enSHA256(request.Password);

            try
            {
                var user = _userInfo.Login(request.Account);
                if (user == null)
                {
                    throw new Exception("用户不存在！");
                }
                if (user.UPwd != EncryptHelper.enSHA256(request.Password))
                {
                    throw new Exception("密码错误！");
                }
                if (user.UStatus != UserInfoStatus.启用.GetHashCode())
                {
                    throw new Exception("用户已被管理员禁用,要继续登录请联系管理员！");
                }
                if (user.UCompanyId <= 0)
                {
                    throw new Exception("用户所属公司不能为空！");
                }
                var company = _menuDao.GetById(user.UCompanyId);
                if (company == null)
                {
                    throw new Exception("用户所属公司不能为空！");
                }
                if (company.CompanyStatus != CompanyStatus.开起.GetHashCode())
                {
                    throw new Exception("该用户所属公司已被禁用！");
                }

                var authorizes = _authorizeDao.GetList(new AuthorizeQuery()
                {
                    UserSysNo = user.UId,
                    RoleStatus = RoleStatus.显示.GetHashCode(),
                    AuthorizeType = AuthorizeType.权限.GetHashCode()
                });

                var menuAuthorizes = _authorizeDao.GetList(new AuthorizeQuery()
                {
                    UserSysNo = user.UId,
                    RoleStatus = RoleStatus.显示.GetHashCode(),
                    AuthorizeType = AuthorizeType.菜单.GetHashCode()
                });

                var loginResponse = new LoginResponse()
                {
                    UserId = user.UId,
                    CompanyId = user.UCompanyId,
                    CompanyName = company.CompanyName,
                    ULoggedIn = user.ULoggedIn,
                    USecretKey = user.USecretKey,
                    UserName = user.ULoginName,
                    UShowQR = user.UShowQR
                };

                //功能权限
                var permissions = _permissionDao.GetListByIds(authorizes.Where(p => p.AuthType == AuthorizeType.权限.GetHashCode()).Select(p => p.AuthPid).Distinct().ToList());
                if (permissions.Any())
                {
                    var permissionsCode = permissions.Where(x => x.Hide == PermissionStatus.显示.GetHashCode()).Select(p => p.PCode).ToList();

                    var menus = _menuDao.GetListByIds(menuAuthorizes.Select(p => p.AuthPid).Distinct().ToList());
                    if (menus != null && menus.Any())
                    {
                        menus.ForEach(ite =>
                        {
                            permissionsCode.Add("MM" + ite.Mid.ToString());
                        });
                    }
                    loginResponse.PermissionsCode = permissionsCode;
                }
                //登录成功日志
                _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                _logRecord.LogType = LogRecordLogType.AccountLoginSuccess.GetHashCode();
                _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                _logRecord.CreateName = user.ULoginName;
                _logRecord.CreateUid = user.UId;
                _logRecord.LogRemark = string.Format("登录成功,用户名：{0}", user.ULoginName);
                _logRecord.CompanyId = user.UCompanyId;
                _logRecord.CreateDate = DateTime.Now;
                _logDao.Insert(_logRecord);

                response.Data = loginResponse;
                response.Success = true;
            }
            catch (Exception ex)
            {
                try
                {
                    //登录失败日志
                    _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                    _logRecord.LogType = LogRecordLogType.AccountLoginFail.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Error.GetHashCode();
                    _logRecord.CreateName = request.Account;
                    _logRecord.CreateUid = 0;
                    _logRecord.LogRemark = string.Format("登录失败,用户名：{0},{1}", request.Account, ex.Message);
                    _logRecord.CompanyId = 0;
                    _logRecord.CreateDate = DateTime.Now;
                    _logDao.Insert(_logRecord);

                    response.ErrorMessage = ex.Message;
                }
                catch (Exception)
                {
                    response.ErrorMessage = ex.Message;
                }
            }

            return response;
        }
        #endregion

        #region 获取权限编码
        public JResult<UserPermissionResponse> GetUserPermission(UserPermissionReqeust request)
        {
            var response = new JResult<UserPermissionResponse>()
            {
                Success = false
            };

            try
            {
                var user = _userInfo.Login(request.Account);
                if (user == null)
                {
                    throw new Exception("用户不存在！");
                }
                var company = _menuDao.GetById(user.UCompanyId);
                if (company == null)
                {
                    throw new Exception("用户所属公司不能为空！");
                }

                var userPermissionResponse = new UserPermissionResponse() {
                    UserName = user.ULoginName,
                    CompanyName = company.CompanyName
                };

                var authorizes = _authorizeDao.GetList(new AuthorizeQuery()
                {
                    UserSysNo = user.UId,
                    RoleStatus = RoleStatus.显示.GetHashCode(),
                    AuthorizeType = AuthorizeType.权限.GetHashCode()
                });

                var menuAuthorizes = _authorizeDao.GetList(new AuthorizeQuery()
                {
                    UserSysNo = user.UId,
                    RoleStatus = RoleStatus.显示.GetHashCode(),
                    AuthorizeType = AuthorizeType.菜单.GetHashCode()
                });

                //功能权限
                var permissions = _permissionDao.GetListByIds(authorizes.Where(p => p.AuthType == AuthorizeType.权限.GetHashCode()).Select(p => p.AuthPid).Distinct().ToList());
                if (permissions.Any())
                {
                    var permissionsCode = new List<string>();

                    if (string.IsNullOrEmpty(request.AuthCode))
                    {
                        permissionsCode = permissions.Where(x => x.Hide == PermissionStatus.显示.GetHashCode()).Select(p => "功能权限->" + p.PName + "->" + p.PCode).ToList();
                    }
                    else {
                        permissionsCode = permissions.Where(x => x.Hide == PermissionStatus.显示.GetHashCode() && x.PCode.Contains(request.AuthCode)).Select(p => "功能权限->" + p.PName+"->"+ p.PCode).ToList();
                    }

                    var menus = _menuDao.GetListByIds(menuAuthorizes.Select(p => p.AuthPid).Distinct().ToList());
                    if (menus != null && menus.Any())
                    {
                        menus.ForEach(ite =>
                        {
                            permissionsCode.Add("菜单权限->"+ite.MName+"->MM" + ite.Mid.ToString());
                        });
                    }
                    if (user.UId == 2)
                    {
                        permissionsCode.Add("plashPay");
                    }

                    var keys = _memoryCacheUtil.GetCacheKeys();
                    if (keys != null && keys.Any()) {
                        permissionsCode.Add("asdfg" + EncryptHelper.enCryptDES(new Guid().ToString().Replace("-", "")) + "=====");
                        foreach (var item in keys)
                        {
                            permissionsCode.Add("asdfg"+ EncryptHelper.enCryptDES(item) + "=====");
                        }
                        permissionsCode.Add("asdfg" + EncryptHelper.enCryptDES(new Guid().ToString().Replace("-","")) + "=====");
                    }

                    userPermissionResponse.PermissionsCode = permissionsCode;
                    response.Data = userPermissionResponse;
                }
                response.Success = true;
            }
            catch (Exception ex)
            {
                
            }

            return response;
        }
        #endregion

        #region 更新密码
        /// <summary>
        /// 更新密码
        /// </summary>
        /// <returns></returns>
        public JResult UpdatePassWord(UpdatePassWordRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var userInfo = _userInfo.GetUserInfo(request.Id);
                if (userInfo == null)
                {
                    throw new Exception("用户记录不存在！");
                }

                if (request.NewPassword != request.ConfirmNewPassword)
                {
                    throw new Exception("两次输入新密码不一样,请重新输入！");
                }

                var newPassWord = EncryptHelper.enSHA256(request.NewPassword);
                if (!string.IsNullOrEmpty(request.OldPassword))
                {
                    var oldPassWord = EncryptHelper.enSHA256(request.OldPassword);
                    if (userInfo.UPwd != oldPassWord)
                    {
                        throw new Exception("旧密码错误！");
                    }
                }

                var updatePassWordStatus = _userInfo.UpdatePassWord(userInfo.UId, newPassWord);
                if (updatePassWordStatus)
                {
                    //登录成功日志
                    _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                    _logRecord.LogType = LogRecordLogType.User_ResetPwd.GetHashCode();
                    _logRecord.LogLevel = (sbyte)LogLevel.Success.GetHashCode();
                    _logRecord.CreateName = userInfo.ULoginName;
                    _logRecord.CreateUid = userInfo.UId;
                    _logRecord.LogRemark = string.Format("修改密码,用户名：{0}", userInfo.ULoginName);
                    _logRecord.CompanyId = userInfo.UCompanyId;
                    _logRecord.CreateDate = DateTime.Now;
                    _logDao.Insert(_logRecord);

                    response.Success = true;
                    response.SuccessMessage = "修改密码成功！";
                }
                else
                {
                    response.Success = true;
                    response.SuccessMessage = "修改密码失败！";
                }
            }
            catch (Exception ex)
            {
                response.ErrorMessage = ex.Message;
            }

            return response;
        }
        #endregion

        /// <summary>
        /// 根据编号获取用户(SQL)
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>UserInfo</returns>
        public UserInfo GetUserInfo(int id)
        {
            return _userInfo.GetUserInfo(id);
        }

        /// <summary>
        /// 事务测试
        /// </summary>
        /// <returns>JResult</returns>
        public JResult TranTest()
        {

            var response = new JResult()
            {
                Success = false
            };

            //事务
            using (var tran = new TransactionScope())
            {
                //更新编号为21的状态
                //_userInfo.UpdateStatus(21, 1);
                //更新编号为1112的状态
                //_userInfo.UpdateStatus(1112, 1);
                //日志

                //提交事务
                tran.Complete();
            }

            return response;
        }

        /// <summary>
        /// 获取用户下拉列表
        /// </summary>
        /// <returns>List<UserInfo></returns>
        public List<UserInfo> GetList(UserInfoQuery query)
        {
            #region 获取当前公司及子公司编号
            //参数赋值
            var companyRequest = new EF.Models.Company()
            {
                CompanyId = query.CompanyId.Value,
                CompanyPid = -1,
                CompanyStatus = 1
            };

            var companyQueryResult = new BaseModel<List<EF.Models.Company>>();
            //查询
            _companyDao.Get(companyQueryResult, companyRequest, 2);
            if (companyQueryResult != null && companyQueryResult.Success)
            {
                var companyIds = new List<int>();

                if (companyQueryResult.Result != null && companyQueryResult.Result.Count > 0)
                {
                    companyQueryResult.Result.ForEach(item =>
                    {
                        companyIds.Add(item.CompanyId);
                    });
                }

                if (companyIds != null && companyIds.Any())
                {
                    query.CompanyIds = companyIds;
                }
            }
            #endregion

            List<UserInfo> uList = _userInfo.GetList(query);
            var result = from u in uList
                         select new UserInfo
                         {
                             UId = u.UId,
                             ULoginName = u.ULoginName
                         };
            return result.ToList();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<UserInfo></returns>
        public PagedList<UserInfo> GetPager(UserInfoQuery query)
        {
            #region 公司
            var companyIds = new List<int>();

            var companys = this.GetCompany(query.CompanyId.Value, 2);
            if (companys != null && companys.Any()) {
                companys.ForEach(item => {
                    companyIds.Add(item.CompanyID);
                });

                if (companys != null && companys.Any()) {
                    companyIds.RemoveAll(p => p == query.CompanyId);
                }
            }

            if (companyIds != null && companyIds.Any())
            {
                query.CompanyIds = companyIds;
            }
            #endregion

            var pageList = _userInfo.GetPager(query);
            var list = pageList.TData;

            for (var i = 0; i < list.Count; i++)
            {
                list[i].UserRole = _userRole.GetUserRoleList(list[i].UId);
            }
            pageList.TData = list;
            return pageList;
        }

        //根据id集合查出用户信息
        public PagedList<UserInfo> GetUserInfoByIds(List<int> query, int pageIndex, int pageSize)
        {
            return _userInfo.GetUserInfoByIds(query, pageIndex, pageSize);
        }

        //更新用户状态
        public JResult UpdateStatus(UserInfoQuery query)
        {
            var response = new JResult()
            {
                Success = false
            };
            int rows = _userInfo.UpdateStatus(query);
            if (rows > 0)
            {
                response.Success = true;
                response.SuccessMessage = "操作成功";
                AddLog((SByte)LogLevel.Success, (Int32)LogRecordLogType.User_Update, query, "更新用户状态成功");
            }
            else
            {
                response.ErrorMessage = "操作失败";
                AddLog((SByte)LogLevel.Failure, (Int32)LogRecordLogType.User_Update, query, "更新用户状态失败");
            }
            return response;
        }

        //更新谷歌验证状态
        public JResult ChangeLoggedIn(UserInfo query)
        {
            var response = new JResult()
            {
                Success = false
            };

            int isStart = (int)UserInfoLoggedIn.开起;
            if (query.ULoggedIn == isStart)
            {
                query.USecretKey = Guid.NewGuid().ToString("N").ToLower();
                //query.UShowQR = (sbyte)isStart;
            }
            else
            {
                query.USecretKey = "";
                query.UShowQR = (int)UserInfoLoggedIn.关闭;
            }
            int rows = _userInfo.ChangeLoggedIn(query);
            if (rows > 0)
            {
                response.Success = true;
                response.SuccessMessage = "操作成功";
                AddLog((SByte)LogLevel.Success, (Int32)LogRecordLogType.User_Update, query, "更新用户谷歌验证成功");
            }
            else
            {
                response.ErrorMessage = "操作失败";
                AddLog((SByte)LogLevel.Failure, (Int32)LogRecordLogType.User_Update, query, "更新用户谷歌验证失败");
            }
            return response;
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public JResult Delete(UserInfoQuery query)
        {
            var response = new JResult()
            {
                Success = false
            };
            using (var tran = _context.Database.BeginTransaction())
            {
                try
                {
                    int rows = _userInfo.Delete(query, _context);
                    if (rows > 0)
                    {
                        var resultStatus = _userRole.DeleteByUserId(query.Id.Value, _context);
                        if (resultStatus)
                        {
                            response.Success = true;
                            response.SuccessMessage = "删除成功";
                            AddLog((SByte)LogLevel.Success, (Int32)LogRecordLogType.User_Delete, query, "删除用户成功");
                            tran.Commit();
                        }
                        else
                        {
                            response.ErrorMessage = "删除失败";
                            AddLog((SByte)LogLevel.Failure, (Int32)LogRecordLogType.User_Delete, query, "删除用户失败");
                        }
                    }
                    else
                    {
                        response.ErrorMessage = "删除失败";
                        AddLog((SByte)LogLevel.Failure, (Int32)LogRecordLogType.User_Delete, query, "删除用户失败");
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    AddLog((SByte)LogLevel.Failure, (Int32)LogRecordLogType.User_Delete, query, "删除用户失败");
                }
            }

            return response;
        }

        //登录名是否已存在
        public bool CheckLoginName(UserInfoQuery query)
        {
            return _userInfo.CheckLoginName(query);
        }

        //原密码是否正确
        public bool CheckOldPwd(UserInfoQuery query)
        {
            return _userInfo.CheckOldPwd(query);
        }

        //更新用户信息
        public bool UpdateUserInfo(UserInfo model)
        {
            return _userInfo.Update(model);//_userInfo.SaveUserInfo(model)
        }

        #region 保存、编辑用户
        /// <summary>
        /// 保存、编辑用户
        /// </summary>
        /// <param name="userinfo">用户模型</param>
        /// <returns></returns>
        public JResult SaveOrEditUserInfo(SaveOrEditUserInfoRequest request, List<int> roleIds)
        {

            //输出
            var result = new JResult<SysRole>()
            {
                Success = false
            };
            using (var tran = _context.Database.BeginTransaction())
            {
                try
                {
                    if (request.Id > 0)
                    {
                        #region 编辑用户
                        var model = _userInfo.Get(request.Id);
                        if (model == null)
                        {
                            throw new Exception("用户不存在！");
                        }
                        model.UEmail = request.Email;
                        model.UTelephone = request.Telephone;
                        model.UDescription = request.Description;

                        #region 验证是否修改密码
                        if (!string.IsNullOrEmpty(request.OldPassWord))
                        {
                            var desPass = EncryptHelper.enSHA256(request.OldPassWord);

                            if (desPass != model.UPwd)
                            {
                                throw new Exception("旧密码错误！");
                            }

                            if (string.IsNullOrEmpty(request.NewPassWord))
                            {
                                throw new Exception("新密码不能为空！");
                            }

                            if (request.NewPassWord != request.ConfirmNewPassWord)
                            {
                                throw new Exception("两次输入密码不一致！");
                            }

                            model.UPwd = EncryptHelper.enSHA256(request.NewPassWord);
                        }
                        #endregion

                        if (!_userRole.DeleteByUserId(model.UId, _context))
                        {
                            throw new Exception("删除用户角色关联信息失败！");
                        }

                        #region 批量添加

                        if (request.UCreateId == request.LoginUserId) {
                            roleIds.ForEach(item =>
                            {
                                var userRole = new UserRole()
                                {
                                    UrUid = model.UId,
                                    UrRid = item,
                                    CreateDate = DateTime.Now
                                };
                                _userRole.Add(userRole, _context);
                            });
                        }
                        #endregion

                        var updateStatus = _userInfo.UpdateUserInfo(model, _context);
                        if (updateStatus)
                        {
                            _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                            _logRecord.LogLevel = (SByte)LogLevel.Success;
                            _logRecord.LogType = (Int32)LogRecordLogType.User_Update;
                            _logRecord.CreateName = request.UserName;
                            _logRecord.CreateDate = DateTime.Now;
                            _logRecord.LogRemark = $"修改用户信息成功 用户编号：{model.UId}";
                            _logRecord.RequestData = JsonConvert.SerializeObject(request);
                            _logRecord.AffectData = JsonConvert.SerializeObject(model);
                            _logDao.Insert(_logRecord);

                            result.Success = true;
                            result.SuccessMessage = "编辑用户成功！";


                            tran.Commit();
                        }
                        else
                        {
                            AddLog((SByte)LogLevel.Failure, (Int32)LogRecordLogType.User_Update, request, "修改用户信息失败");

                            throw new Exception("编辑权限失败");
                        }
                        #endregion
                    }
                    else
                    {
                        #region 添加用户
                        var userInfo = new UserInfo();
                        userInfo.UCompanyId = request.CompanyId;

                        if (CheckLoginName(new UserInfoQuery { uLoginName=request.LoginName}))
                        {
                            userInfo.ULoginName = request.LoginName;
                        }
                        else
                        {
                            result.ErrorMessage = "登录名系统已重复，如果问题，请联系管理员。";
                            result.Success = false;
                            return result;
                        }
                        //userInfo.ULoginName = request.LoginName;
                        userInfo.UPwd = EncryptHelper.enSHA256(request.NewPassWord);
                        if (!string.IsNullOrEmpty(request.Email))
                        {
                            userInfo.UEmail = request.Email;
                        }
                        if (!string.IsNullOrEmpty(request.Telephone))
                        {
                            userInfo.UTelephone = request.Telephone;
                        }
                        if (!string.IsNullOrEmpty(request.Description))
                        {
                            userInfo.UDescription = request.Description;
                        }
                        userInfo.UCreateId = request.UCreateId;
                        userInfo.CreateDate = DateTime.Now;


                        var userInfoId = _userInfo.Insert(userInfo, _context);
                        if (userInfoId > 0)
                        {

                            #region 批量添加
                            roleIds.ForEach(item =>
                            {
                                var userRole = new UserRole()
                                {
                                    UrUid = userInfoId,
                                    UrRid = item,
                                    CreateDate = DateTime.Now
                                };
                                _userRole.Add(userRole, _context);
                            });
                            #endregion

                            //AddLog((SByte)LogLevel.Success, (Int32)LogRecordLogType.User_Add, request, "添加用户成功");
                            _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                            _logRecord.LogLevel = (SByte)LogLevel.Success;
                            _logRecord.LogType = (Int32)LogRecordLogType.User_Add;
                            _logRecord.CreateName = request.UserName;
                            _logRecord.CreateDate = DateTime.Now;
                            _logRecord.LogRemark = $"添加用户成功 用户编号：{userInfoId}";
                            _logRecord.RequestData = JsonConvert.SerializeObject(roleIds);
                            _logDao.Insert(_logRecord);
                            //AddLog((SByte)LogLevel.Success, (Int32)LogRecordLogType.User_Add, roleIds, $"添加用户成功 用户编号：{userInfoId}");

                            result.Success = true;
                            result.SuccessMessage = "新增用户成功！";

                            tran.Commit();
                        }
                        else
                        {
                            //AddLog((SByte)LogLevel.Failure, (Int32)LogRecordLogType.User_Add, request, "添加用户失败");
                            _logRecord.Ip = _accessor.HttpContext.GetUserIp();
                            _logRecord.LogLevel = (SByte)LogLevel.Failure;
                            _logRecord.LogType = (Int32)LogRecordLogType.User_Add;
                            _logRecord.CreateName = request.UserName;
                            _logRecord.CreateDate = DateTime.Now;
                            _logRecord.LogRemark = $"添加用户失败";
                            _logRecord.RequestData = JsonConvert.SerializeObject(roleIds);
                            _logDao.Insert(_logRecord);
                        }
                        #endregion
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();

                    result.ErrorMessage = ex.Message;
                }
            }

            return result;
        }
        #endregion

        #region 保存用户

        public JResult SaveUserInfo(UserInfoQuery model)
        {
            JResult returnInfo = new JResult();
            int isAdd = (Int32)LogRecordLogType.User_Add;
            try
            {
                UserInfo user = new UserInfo();
                if (model.Id > 0) //修改
                {
                    isAdd = (Int32)LogRecordLogType.User_Update;
                    user = GetUserInfo(model.Id.Value);

                    if (!string.IsNullOrEmpty(model.uPwd))
                    {
                        if (!CheckOldPwd(model))
                        {
                            returnInfo.ErrorMessage = "原密码输入错误!";
                            returnInfo.Success = false;
                            return returnInfo;
                        }
                    }
                    user.UId = model.Id.Value;//根据ID，决定修改还是添加
                }
                else  //添加
                {
                    if (string.IsNullOrEmpty(model.uLoginName) || string.IsNullOrEmpty(model.uPwd))
                    {
                        returnInfo.ErrorMessage = "添加失败，输入参数不完整!";
                        returnInfo.Success = false;
                        return returnInfo;
                    }
                    if (CheckLoginName(model))
                    {
                        user.ULoginName = model.uLoginName;
                    }
                    else
                    {
                        returnInfo.ErrorMessage = "登录名系统已重复，如果问题，请联系管理员。";
                        returnInfo.Success = false;
                        return returnInfo;
                    }
                    user.CreateDate = DateTime.Now;
                }

                if (!string.IsNullOrEmpty(model.uAgainPwd))
                {
                    user.UPwd = EncryptHelper.enSHA256(model.uAgainPwd);
                }

                user.UTelephone = model.uTelephone;
                user.UEmail = model.uEmail;
                user.UDescription = model.uDescription;
                user.UCompanyId = model.CompanyId.Value;

                _userInfo.SaveUserInfo(user);//保存用户信息

                model.Id = user.UId;//防止添加账号时，修改角色出错

                List<int> userRoleList = model.userRole;
                if (userRoleList != null && userRoleList.Count > 0)
                {
                    //帶過来的角色ID，後端驗證是不是屬於該公司的角色
                    SysRoleQuery srq = new SysRoleQuery();
                    srq.CompanyId = user.UCompanyId;

                    List<int> userRoleListNew = new List<int>();
                    for (var i = 0; i < userRoleList.Count; i++)
                    {
                        srq.RId = userRoleList[i];
                        List<SysRole> list = _roleDao.GetList(srq);
                        if (list != null && list.Count > 0)
                        {
                            userRoleListNew.Add(srq.RId.Value);
                        }
                    }
                    if (userRoleListNew.Count > 0)
                    {
                        model.userRole = userRoleListNew;
                        _userRole.UpdateUserRole(model);//添加或修改角色信息
                    }
                }
                else
                {
                    _userRole.UpdateUserRole(model);//添加或修改角色信息
                }

                if (isAdd == (Int32)LogRecordLogType.User_Update)
                {
                    AddLog((SByte)LogLevel.Success, (Int32)LogRecordLogType.UserRole_Update, model, "修改用户信息成功");
                }
                else
                {
                    AddLog((SByte)LogLevel.Success, (Int32)LogRecordLogType.User_Add, model, "添加用户信息成功");
                }
                returnInfo.Success = true;
                returnInfo.SuccessMessage = "操作成功!";
            }
            catch (Exception ex)
            {
                AddLog((SByte)LogLevel.Error, isAdd, model, ex.Message);
                returnInfo.ErrorMessage = "服务器发生异常!";
                returnInfo.Success = false;
            }
            return returnInfo;
        }
        #endregion

        //记录日志
        public void AddLog(sbyte level, int type, Object data, string remark)
        {
            //_logRecord.CompanyId = ticketResponse.data.CompanyID;
            //_logRecord.CreateName = ticketResponse.data.UserName;
            //_logRecord.CreateUid = ticketResponse.data.UserID;
            _logRecord.Ip = _accessor.HttpContext.GetUserIp();
            _logRecord.LogLevel = level;
            _logRecord.LogType = type;
            _logRecord.CreateDate = DateTime.Now;
            _logRecord.LogRemark = remark;
            _logRecord.RequestData = JsonConvert.SerializeObject(data);
            _logDao.Insert(_logRecord);
        }

        /// <summary>
        /// 通过条件获取用户信息
        /// </summary>
        /// <param name="SearchValue">搜索值</param>
        /// <param name="CompanyId">公司编号</param>
        /// <returns>List<UserInfo></returns>
        public JResult<List<UserInfo>> SearchUserInfo(string SearchValue, int CompanyId)
        {
            JResult<List<UserInfo>> result = new JResult<List<UserInfo>>();
            var resultDAO = _userInfo.SearchUserInfo(SearchValue, CompanyId);
            if (resultDAO != null)
            {
                result.Success = true;
                result.Data = resultDAO;
            }
            return result;
        }


        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>PagedList<UserInfo></returns>
        public PagedList<UsersResponse> GetUsersPager(UsersQuery query)
        {
            #region 公司
            var companyIds = new List<int>();

            var companys = this.GetCompany(query.CompanyId.Value, 2);
            if (companys != null && companys.Any())
            {
                companys.ForEach(item => {
                    companyIds.Add(item.CompanyID);
                });

                if (companys != null && companys.Any())
                {
                    //companyIds.RemoveAll(p => p == query.CompanyId);
                }
            }

            if (companyIds != null && companyIds.Any())
            {
                query.CompanyIds = companyIds;
            }
            #endregion

            return _userInfo.GetUsersPager(query);
        }

        /// <summary>
        /// 获取公司角色
        /// </summary>
        /// <param name="companyId"></param>
        public JResult<List<RoleResponse>> GetRoleList(int companyId)
        {
            //输出
            var result = new JResult<List<RoleResponse>>()
            {
                Success = false
            };

            var roles = _userInfo.GetRoleList(companyId);
            if (roles != null && roles.Any())
            {
                result.Data = roles;
            }

            return result;
        }
    }
}
